package com.xiaoxx.common.mybatis;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.xiaoxx.common.base.JwtUser;
import com.xiaoxx.common.result.R;
import com.xiaoxx.utils.JwtUtil;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;

/**
 * @Author HX
 * @Date 2022/2/28 18:31
 */

@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
    @Autowired
    private HttpServletRequest request;

    @Autowired
    private HttpServletResponse response;

    @Override
    public void insertFill(MetaObject metaObject) {
        this.setFieldValByName("createTime", LocalDateTime.now(), metaObject);
        this.setFieldValByName("updateTime", LocalDateTime.now(), metaObject);
        try {
            R<JwtUser> jwtUserR = JwtUtil.getJwtUserR(request, response);
            if (jwtUserR.getCode().equals(R.success().getCode())) {
                JwtUser jwtUser = jwtUserR.getData();
                this.strictInsertFill(metaObject, "createUser", String.class, jwtUser.getUserId());
                this.strictInsertFill(metaObject, "updateUser", String.class, jwtUser.getUserId());
            } else {
                this.strictInsertFill(metaObject, "createUser", String.class, "0");
                this.strictInsertFill(metaObject, "updateUser", String.class, "0");
            }
        } catch (Exception e) {
            this.strictInsertFill(metaObject, "createUser", String.class, "0");
            this.strictInsertFill(metaObject, "updateUser", String.class, "0");
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        this.setFieldValByName("updateTime", LocalDateTime.now(), metaObject);
        try {
            R<JwtUser> jwtUserR = JwtUtil.getJwtUserR(request, response);
            if (jwtUserR.getCode().equals(R.success().getCode())) {
                JwtUser jwtUser = jwtUserR.getData();
                this.strictUpdateFill(metaObject, "updateUser", String.class, jwtUser.getUserId());
            } else {
                this.strictUpdateFill(metaObject, "updateUser", String.class, "0");
            }
        } catch (Exception e) {
            this.strictInsertFill(metaObject, "updateUser", String.class, "0");
        }
    }
}


